package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: AuthenticationInterceptor
 * Package: com.atguigu.lease.web.admin.custom.interceptor
 * Description:
 *
 * @Author 王颖轩
 * @Create 2024/11/22 20:52
 * @Version 1.0
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前端约定token令牌所对应的请求头的键为access_token
        //获取请求头中access_token的值
        String accessToken = request.getHeader("access_token");
        //判断access_token是否为null
        if(accessToken == null) {
            //表示当前请求未携带token，即未登录，响应浏览器未登录状态的Result
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else{
            //表示当前请求携带了token，即已登录，解析token获取登录的userId和username
            Claims claims = JwtUtil.parseToken(accessToken);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            LoginUser loginUser = new LoginUser(userId, username);
            LoginUserContext.setLoginUser(loginUser);
            //放行
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
